package team.yidong.fenda.utils;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

/**
 * Created by xuanlong on 2017/11/15.
 */
@Component
public class RedisUtil {


    public static void subscribeMessage() {

        final String host = "localhost";// Redis服务所在地址

        final int port = 6379;          // 主机端口

        @SuppressWarnings("resource")
        Jedis subJedis = new Jedis(host, port);

        JedisPubSub jedissubSub = new JedisPubSub() {

            public void onUnsubscribe(String channel, int num) {
            }

            public void onSubscribe(String channel, int num) {
            }

            public void onMessage(String channel, String msg) {
                System.out.println(channel + " : " + msg);
            }

            public void onPUnsubscribe(String channel, int num) {
            }

            /*
             * num 订阅数量
             */
            public void onPSubscribe(String channel, int num) {
            }

            /*
             * channel0订阅的channel正则表达式
             * channel 匹配上该正则channel值
             * msg 收到的消息
             */
            public void onPMessage(String channel0, String channel, String msg) {
            }

        };

        /*
         * 启动订阅，当该方法启动时，将阻塞等待消息
         * 说明：
         * 1.subscribe(JedisPubSub jedisPubSub, String... channels)
         *    是常规订阅方法，channel值基于完全匹配,方法中channels是多个要订阅的channel值
         * 2.psubscribe(JedisPubSub jedisPubSub, String... patterns)
         *    是正则订阅方法，channel值基于正则匹配,方法中的patterns是多个订阅到正则表达式
         *    不同的订阅将会触发JedisPubSub中不同的方法
         */
        subJedis.subscribe(jedissubSub, "news", "tvshow");//完全匹配
    }

}

